package cn.itheima.service.impl;

import cn.itheima.dao.CourierRepositroy;
import cn.itheima.domain.Courier;
import cn.itheima.service.CourierService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Set;

/**
 * Created by millions on 2017/7/3.
 */
@Service
@Transactional
public class CourierServiceImpl implements CourierService {

    @Autowired
    private CourierRepositroy courierRepositroy;

    @Override
//    @RequiresPermissions("courier—add")
    public void save(Courier courier) {
        courierRepositroy.save(courier);
    }

    @Override
    public Page<Courier> findPageData(Pageable pageable, Specification<Courier> specification) {

        return courierRepositroy.findAll(specification,pageable);
    }

    @Override
    public void delBatch(String[] split) {

        for (String idStr : split) {
            Integer id = Integer.parseInt(idStr);
            courierRepositroy.updateDelTag(id);
        }
    }

    /**
     * 查询没有关联定区的快递员
     * @return
     */
    @Override
    public List<Courier> findNoAssociation() {

        Specification<Courier> specification = new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.isEmpty(root.get("fixedAreas").as(Set.class));
                return predicate;
            }
        };
        return courierRepositroy.findAll(specification);

    }
}
